package doc

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

// ----------------------------- 使用http 直接访问es,还是不太方便的传参数不太好处理 -------------------
var host = "http://localhost:9200/"

// HttpEs http直接访问es
func HttpEs() {
	resp, err := http.Get(host)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	//body, err := ioutil.ReadAll(resp.Body)
	body, err := io.ReadAll(resp.Body)
	fmt.Println(string(body))
	//fmt.Println(resp.StatusCode)
	if resp.StatusCode == 200 {
		fmt.Println("连接es成功")
	}
}

// 查看是否存在blog索引,不存在就创建,否则返回成功
func createIndexDatabase(indexName string) {
	opeUrl := host + indexName
	fmt.Println("请求信息", opeUrl)
	resp, err := http.Head(opeUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	fmt.Println(string(body))
	fmt.Println(resp.StatusCode)
	if resp.StatusCode == 200 {
		fmt.Println(indexName + "索引已存在")
	} else {
		fmt.Println("即将创建索引" + indexName)
		createInfo, err := http.NewRequest("PUT", opeUrl, nil)
		if err != nil {
			fmt.Println("创建失败", err)
			return
		}
		fmt.Println("创建成功", createInfo)
	}
}

// 查询数据
func showIndexItem() {
	opeUrl := host + "blog/user/10"
	res, err := http.Get(opeUrl)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(res)
}

// 添加索引数据  body io.Reader
func addIndexItem(opeUrl string) {
	opeUrl = host + "blog/user/11"
	payload := strings.NewReader("{\"name\":\"张瑀楠\"}")
	payload = strings.NewReader("{\"id\": 5,\"user_name\": \"优酷\",\"password\": \"1234567\",\"address\": \"北京优酷大厦\"}")
	fmt.Println("操作")
	resp, err := http.NewRequest("PUT", opeUrl, payload)
	if err != nil {
		fmt.Println("操作失败", err)
		return
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
	//if resp.StatusCode == 200 {
	//	fmt.Println("操作成功")
	//}
	fmt.Println("返回结果", resp)
}
